package com.wxy.ej.flow.modules.taskflow.service.nodeExecuteStrategy.strategy.nosql;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rt.easyjava.common.base.Result;
import com.rt.easyjava.common.config.SpringContextBaseHolder;
import com.rt.easyjava.common.utils.others.StringUtils;
import com.wxy.ej.flow.modules.taskflow.dto.DataDto;
import com.wxy.ej.flow.modules.taskflow.dto.NodeDto;
import com.wxy.ej.flow.modules.taskflow.facade.CollectionDataApi;
import com.wxy.ej.flow.modules.taskflow.service.nodeExecuteStrategy.NodeStrategy;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class NosqlPageStrategy extends NodeStrategy {

    @Override
    public Result action(NodeDto node, JSONObject flowDataJson, DataDto dataDto) throws Exception{
        CollectionDataApi collectionDataApi = SpringContextBaseHolder.getFeignBean("collectionDataApi", CollectionDataApi.class);

        // 查询条件
        Object uiInParam = dataDto.getUiInParam();
        String  paramString= JSON.toJSONString(uiInParam);
        JSONObject queryJsonObject = JSONObject.parseObject(paramString);

        // 指定mongodb集合
        String collectionName = "collection_"+dataDto.getTaskFlowId();

        //query api
        Result result = collectionDataApi.page(queryJsonObject, collectionName);
        List list = result.getList();
        int total = result.getTotal();

        // save data: total
        String inDataToStorageMapVar4PageTotal = node.getDefineVarName4PageTotal();
        dataDto.getStorageDataVarMap().put(inDataToStorageMapVar4PageTotal, total);
        dataDto.getLogList().add("保存数据在"+inDataToStorageMapVar4PageTotal+"里，总记录数："+total);

        // 保存数据: list
        String inDataToStorageMapVar = node.getDefineVarName();
        dataDto.getStorageDataVarMap().put(inDataToStorageMapVar, list);
        dataDto.getLogList().add("保存数据在"+inDataToStorageMapVar+"里，记录数："+list.size());

        return Result.builder();
    }
}
